package com.liangxy.news.ui.detail;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.liangxy.news.R;
import com.liangxy.news.api.ApiClient;
import com.liangxy.news.api.NewsApiService;
import com.liangxy.news.api.NewsDetailResponse;
import com.liangxy.news.database.AppDatabase;
import com.liangxy.news.model.News;
import com.liangxy.news.model.NewsDetail;
import com.liangxy.news.model.User;
import com.liangxy.news.model.UserHistory;
import com.liangxy.news.ui.viewmodel.NewsDetailViewModel;
import com.liangxy.news.util.NetworkUtils;
import com.liangxy.news.util.SharedPreferencesManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Activity for displaying news detail
 */
public class NewsDetailActivity extends AppCompatActivity {
    
    private static final String TAG = "NewsDetailActivity";
    public static final String EXTRA_NEWS_ID = "extra_news_id";
    
    private Toolbar toolbar;
    private TextView tvTitle;
    private TextView tvSource;
    private TextView tvDate;
    private ImageView ivThumbnail;
    private WebView webView;
    private ProgressBar progressBar;
    
    private String newsId;
    private ExecutorService executorService;
    private SharedPreferencesManager preferencesManager;
    private NewsDetailViewModel viewModel;
    private String currentUserId;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);
        
        // Initialize components
        toolbar = findViewById(R.id.toolbar);
        tvTitle = findViewById(R.id.tvTitle);
        tvSource = findViewById(R.id.tvSource);
        tvDate = findViewById(R.id.tvDate);
        ivThumbnail = findViewById(R.id.ivThumbnail);
        webView = findViewById(R.id.webView);
        progressBar = findViewById(R.id.progressBar);
        
        // Setup toolbar
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle(R.string.news_detail);
        }
        
        // Get news ID from intent
        newsId = getIntent().getStringExtra(EXTRA_NEWS_ID);
        if (newsId == null || newsId.isEmpty()) {
            Log.e(TAG, "News ID is null or empty");
            Toast.makeText(this, R.string.error_news_not_found, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        Log.d(TAG, "Loading news with ID: " + newsId);
        executorService = Executors.newSingleThreadExecutor();
        preferencesManager = new SharedPreferencesManager(this);
        currentUserId = preferencesManager.getUserId();
        
        // 保存用户浏览历史
        saveUserBrowsingHistory();
        
        // Setup WebView
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        
        // Setup ViewModel
        viewModel = new ViewModelProvider(this).get(NewsDetailViewModel.class);
        observeViewModel();
        
        // Load news detail
        viewModel.setUserId(currentUserId);
        viewModel.loadNewsDetail(newsId);
    }
    
    /**
     * 保存用户浏览历史
     */
    private void saveUserBrowsingHistory() {
        if (currentUserId != null && !currentUserId.isEmpty() && newsId != null && !newsId.isEmpty()) {
            // 使用synchronized代码块确保数据库操作的原子性
            executorService.execute(() -> {
                synchronized (NewsDetailActivity.class) {
                    try {
                        AppDatabase database = AppDatabase.getInstance(getApplicationContext());
                        
                        // 先检查数据库中是否已存在该记录
                        boolean exists = false;
                        try {
                            // 这里简单查询一下是否有该记录
                            UserHistory history = database.historyDao().getUserHistoryByUserAndNews(currentUserId, newsId);
                            exists = (history != null);
                        } catch (Exception e) {
                            // 忽略查询错误，不影响保存操作
                            Log.w(TAG, "查询历史记录时出错: " + e.getMessage());
                        }
                        
                        // 插入或更新历史记录
                        database.historyDao().insert(currentUserId, newsId);
                        
                        // 确保数据已写入持久化存储
                        database.getOpenHelper().getWritableDatabase().execSQL("PRAGMA wal_checkpoint(PASSIVE)");
                        
                        if (exists) {
                            Log.d(TAG, "更新用户浏览历史: userId=" + currentUserId + ", newsId=" + newsId);
                        } else {
                            Log.d(TAG, "保存新的用户浏览历史: userId=" + currentUserId + ", newsId=" + newsId);
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "保存用户浏览历史失败: " + e.getMessage(), e);
                    }
                }
            });
        } else {
            Log.w(TAG, "未保存浏览历史: userId=" + currentUserId + ", newsId=" + newsId);
        }
    }
    
    /**
     * Observe view model
     */
    private void observeViewModel() {
        viewModel.getNews().observe(this, this::displayNews);
        
        viewModel.getNewsDetail().observe(this, newsDetail -> {
            if (newsDetail != null) {
                progressBar.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
                
                Log.d(TAG, "收到新闻详情数据: ID=" + newsDetail.getNewsId() + 
                      ", Title=" + newsDetail.getTitle() + 
                      ", Content长度=" + (newsDetail.getContent() != null ? newsDetail.getContent().length() : 0));
                
                String content = newsDetail.getContent();
                if (content == null || content.isEmpty()) {
                    content = "<h1>内容加载失败</h1><p>新闻详情内容为空，请返回重试。</p>";
                    Log.e(TAG, "新闻详情内容为空: " + newsDetail.getNewsId());
                }
                
                // 构建完整HTML并加载
                String html = formatHtmlContent(newsDetail.getTitle(), content);
                webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
            } else {
                Log.e(TAG, "收到的新闻详情为null");
                progressBar.setVisibility(View.GONE);
                Toast.makeText(this, "加载新闻详情失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });
        
        viewModel.getIsLoading().observe(this, this::showLoading);
        
        viewModel.getErrorMessage().observe(this, errorMsg -> {
            if (errorMsg != null && !errorMsg.isEmpty()) {
                Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    /**
     * Display news
     */
    private void displayNews(News news) {
        if (news == null) {
            showEmptyState();
            return;
        }
        
        // Display title
        String title = news.getTitle();
        if (title != null && !title.isEmpty()) {
            tvTitle.setText(title);
        } else {
            tvTitle.setText(R.string.no_title);
        }
        
        // Display source
        String source = news.getSource();
        if (source != null && !source.isEmpty()) {
            tvSource.setText(source);
        } else {
            String author = news.getAuthorName();
            if (author != null && !author.isEmpty()) {
                tvSource.setText(author);
            } else {
                tvSource.setText(R.string.unknown_source);
            }
        }
        
        // Display date
        String date = news.getDate();
        if (date != null && !date.isEmpty()) {
            tvDate.setText(date);
        } else {
            tvDate.setVisibility(View.GONE);
        }
        
        // Display thumbnail if available
        String thumbnail = news.getThumbnail();
        if (thumbnail != null && !thumbnail.isEmpty()) {
            ivThumbnail.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(thumbnail)
                    .placeholder(R.drawable.placeholder_image)
                    .error(R.drawable.placeholder_image)
                    .into(ivThumbnail);
        } else {
            ivThumbnail.setVisibility(View.GONE);
        }
    }
    
    /**
     * Format HTML content
     */
    private String formatHtmlContent(String title, String content) {
        // Add CSS styling to the HTML content with title
        return "<html><head>" +
                "<meta name='viewport' content='width=device-width, initial-scale=1.0'>" +
                "<style type='text/css'>" +
                "body{padding:15px; font-size:16px; line-height:1.5; font-family: Arial, sans-serif;}" +
                "img{max-width:100%; height:auto; display:block; margin:10px auto;}" +
                "h1{color:#333; margin-bottom:15px; font-size:20px;}" +
                "h2,h3{color:#333; margin-bottom:15px;}" +
                "p{margin-bottom:10px; color:#333;}" +
                ".news-title{font-weight:bold; font-size:22px; color:#000; margin-bottom:20px;}" +
                "</style></head><body>" +
                "<div class='news-title'>" + title + "</div>" +
                content +
                "</body></html>";
    }
    
    /**
     * Show empty state
     */
    private void showEmptyState() {
        tvTitle.setText(R.string.error_loading_news_detail);
        tvSource.setText("");
        tvDate.setText("");
        ivThumbnail.setVisibility(View.GONE);
        webView.loadData("<html><body><p>" + getString(R.string.error_loading_news_detail) + "</p></body></html>", 
                "text/html", "utf-8");
    }
    
    /**
     * Show/hide loading indicator
     */
    private void showLoading(boolean isLoading) {
        progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (executorService != null) {
            executorService.shutdown();
        }
        if (webView != null) {
            webView.destroy();
        }
    }
} 